//
//  UserAccount.swift
//  Weibo
//
//  Created by 明丽 on 16/1/13.
//  Copyright © 2016年 明丽. All rights reserved.
//

import UIKit

class UserAccount: NSObject ,NSCoding{
    var access_token: String?
    //access_token的生命周期，单位是秒数 token 过多少秒会过期
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expires_date: NSDate?

    var uid: String?
    var name: String?
    var avatar_large: String?
    //kvc设置初始值
    init(dict: [String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
 //过滤key
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
//    //重写对象的描述信息
override var description: String {
   let keys = ["access_token","expires_in","uid","name","avatar_large"]
    
    let dict = self.dictionaryWithValuesForKeys(keys)
    return dict.description
    
    }
    
//   override func valueForUndefinedKey(key: String) -> AnyObject?{
//    return nil;
//    }
//    
    
    
    //保存自定义对象到沙河
    
    //保存自定义对象
    func saveAccount() {
        //保存到沙盒中
        //拼接路径 在XCode 7.0正式版中 被搞丢了
        //stringByAppendingbyPathCommant
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        print(path)
        //将对象保存到沙盒路径中
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    
    //获取沙河中的归档对象
    class  func loadUserAccount() -> UserAccount? {
        
            let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount {
        return account
    }
    
    return nil

    }
    
    //解归档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        //如果是基本数据类型 可以直接 解归档到具体类型
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        
        
        
        
    }

    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expires_date, forKey: "expires_date")

        
        
    }

    

}
